/*    This file is part of Nephite Exchange.
 *
 *    Nephite Exchange is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    Nephite Exchange is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with Nephite Exchange.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.icub3d.nephiteexchange.client;

import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.ui.Label;

public class JSONRequest implements RequestCallback {
	public static final String JSON_URL = "/nephite-exchange-data/index/";
	public static final int STATUS_CODE_OK = 200;
	
	protected Request request = null;
	protected String message = null;
	
	protected Label errorLabel;
	protected ProcessJSONRequest processor;
	
	public JSONRequest (Label errorLabel, ProcessJSONRequest processor) {
		this.errorLabel = errorLabel;
		this.processor = processor;
	}
	
	public void RequestJSON(String getLine) {
		String url = URL.encode(JSON_URL + getLine);

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

		try {
			 request = builder.sendRequest(null, this);
		} catch (RequestException e) {
			displayError("Couldn't retrieve JSON due to exception: "
					+ e.getMessage());
		}
	}

	@Override
	public void onError(Request request, Throwable exception) {
		displayError("Couldn't retrieve JSON during request.");
	}

	@Override
	public void onResponseReceived(Request request, Response response) {
		if (STATUS_CODE_OK == response.getStatusCode()) {
			processor.processJSONRequest(response.getText());
		} else {
			displayError("Couldn't retrieve JSON ("
					+ response.getStatusText() + ")");
		}
	}
	
    public void displayError(String string) {
    	errorLabel.setText(string);	
	}
}
